package com.jpa.lgt.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;


/**
 * @author lgt
 * @time 2018/11/27
 * @description：创建自定义助手类
 *               SimpleChannelInboundHandler 对于请求来说，相当于入站和入境
 */
public class CustomHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        //获取channel
        Channel channel=ctx.channel();
        if (msg instanceof HttpRequest){
            //显示客户端的远程地址
            System.out.println(channel.remoteAddress());

            //定义发送的数据消息(Unpooled为深拷贝处理类)
            ByteBuf content= Unpooled.copiedBuffer("hello Netty!", CharsetUtil.UTF_8);

            //构建一个http response
            FullHttpResponse response= new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK,content);

            //增加响应的数据类型
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            //增加响应的数据长度
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());

            //把相应内容刷新在客户端
            ctx.writeAndFlush(response);
        }

    }
}
